import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import rateLimit from 'express-rate-limit';
import dotenv from 'dotenv';
import { executeRoutes } from './routes/execute';
import { analyzeRoutes } from './routes/analyze';
import { evaluateRoutes } from './routes/evaluate';
import { errorHandler } from './middleware/errorHandler';
import { logger } from './utils/logger';

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 7777;

// 安全中间件
app.use(helmet());
app.use(cors());

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 每个IP在windowMs时间内最多请求次数
  standardHeaders: true,
  legacyHeaders: false,
});
app.use(limiter);

// 日志中间件
app.use(morgan('combined', { stream: { write: (message) => logger.info(message.trim()) } }));

// 请求解析
app.use(bodyParser.json({ limit: '1mb' }));

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'OK' });
});

// 路由
app.use('/api/execute', executeRoutes);
app.use('/api/analyze', analyzeRoutes);
app.use('/api/evaluate', evaluateRoutes);

// 处理404
app.use((req, res) => {
  res.status(404).json({ message: 'Not Found' });
});

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
app.listen(PORT, () => {
  logger.info(`Code execution sandbox running on port ${PORT}`);
});

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  logger.error('Uncaught Exception:', error);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

export default app; 